import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';
import 'package:xvideos/assets_tool/app_colors.dart';
import 'package:xvideos/assets_tool/images.dart';
import 'package:xvideos/hj_model/home/home_tabs_entity.dart';
import 'package:xvideos/hj_page/cartoon_business/cartoon_sub_detail_page.dart';
import 'package:xvideos/hj_page/cartoon_business/cartoon_sub_module_page.dart';
import 'package:xvideos/hj_page/home_business/home_sub_module/home_tab_section_page.dart';
import 'package:xvideos/hj_page/home_business/home_sub_module/home_tab_sort_page.dart';
import 'package:xvideos/hj_page/home_business/widget/home_limit_activity_widget.dart';
import 'package:xvideos/hj_page/main_page/provider/module_provider.dart';
import 'package:xvideos/hj_utils/holiday_theme.dart';
import 'package:xvideos/hj_utils/screen.dart';
import 'package:xvideos/tools_base/indicator/custom_tab_indicator.dart';
import 'package:xvideos/tools_base/loading/loading_center_widget.dart';
import 'package:xvideos/tools_base/widget/keep_alive_widget.dart';

import '../main_page/provider/bottom_bar_provider.dart';
import '../pre_sale/pre_sale_entry_widget.dart';
import '../pre_sale/pre_sale_provider.dart';
import 'home_main_logic.dart';
import 'hs_home_drawer.dart';
import 'search_page/widget/common_search_bar_view.dart';

class HomeMainPage extends StatefulWidget {
  const HomeMainPage({super.key});

  @override
  State<HomeMainPage> createState() => _HomePageState();
}

class _HomePageState extends State<HomeMainPage> with SingleTickerProviderStateMixin {
  HomeMainLogic logic = HomeMainLogic();

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Color(0xff050f17),
      child: GetBuilder<HomeMainLogic>(
        init: logic,
        tag: "HomeMainLogic",
        builder: (_) {
          return Consumer<HomeModuleProvider>(
            builder: (ctx, provider, __) {
              return Stack(
                fit: StackFit.expand,
                children: [
                  if (holidayTheme.openHoliday) ...[
                    Container(color: AppColors.primaryColor),
                    Positioned(
                      top: 0,
                      left: 0,
                      right: 0,
                      child: Image.asset(HolidayTheme.theme.mainBg, fit: BoxFit.fitWidth),
                    ),
                  ],
                  Scaffold(
                    key: logic.globalKey,
                    backgroundColor: holidayTheme.openHoliday ? Colors.transparent : null,
                    endDrawer: Builder(builder: (_) => HSHomeDrawer(logic)),
                    body: () {
                      if (logic.isLoadingData) {
                        return LoadingCenterWidget();
                      } else {
                        return Column(
                          children: [
                            Container(
                              color: Colors.black,
                              padding: EdgeInsets.only(top: screen.paddingTop),
                              height: kToolbarHeight + screen.paddingTop,
                              child: CommonSearchBarView(logic: logic),
                            ),
                            Expanded(
                              child: HsHomeTabView(
                                key: ValueKey(logic.tabViewValueKey),
                                logic: logic,
                              ),
                            ),
                          ],
                        );
                      }
                    }(),
                  ),
                  Positioned(
                    right: 12,
                    bottom: 40,
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.end,
                      crossAxisAlignment: CrossAxisAlignment.end,
                      children: [
                        HomeLimitActivityWidget(margin: EdgeInsets.only(bottom: 16)),
                        LuckyDrawButton(margin: EdgeInsets.only(bottom: 24)),
                        PreSaleEntryWidget(),
                      ],
                    ),
                  ),
                ],
              );
            },
          );
        },
      ),
    );
  }
}

class HsHomeTabView extends StatefulWidget {
  final HomeMainLogic logic;
  final bool isDarkStyle;

  HsHomeTabView({
    super.key,
    required this.logic,
    this.isDarkStyle = false,
  });

  @override
  State<StatefulWidget> createState() {
    return _HsHomeTabViewState();
  }
}

class _HsHomeTabViewState extends State<HsHomeTabView> with TickerProviderStateMixin {
  HomeMainLogic get logic => widget.logic;
  late TabController tabController;

  bool get isDarkStyle => widget.isDarkStyle;

  @override
  void initState() {
    super.initState();
    tabController =
        TabController(initialIndex: logic.selectedTabIndex, length: logic.homePageTabArr.length, vsync: this);
    tabController.addListener(_listenerCallback);
    logic.tabController = tabController;
  }

  void _listenerCallback() {
    if (!tabController.indexIsChanging) {
      if (widget.isDarkStyle) {
        DarkwebBottomProvider().setSrollController(tabController.index);
      } else {
        HomeBottomProvider().setSrollController(tabController.index);
      }
    }
  }

  //lld_title.png
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Container(
          height: 48.h,
          color: Colors.black,
          child: TabBar(
            tabAlignment: TabAlignment.start,
            tabs: logic.homePageTabArr
                .map((e) => Container(
                      padding: EdgeInsets.symmetric(horizontal: 14.w),
                      alignment: Alignment.center,
                      child: Text(e.moduleName ?? ''),
                    ))
                .toList(),
            isScrollable: true,
            padding: EdgeInsets.only(bottom: 2),
            labelPadding: EdgeInsets.zero,
            unselectedLabelStyle: TextStyle(fontSize: 14),
            unselectedLabelColor: Color(0x73FFFFFF),
            labelStyle: TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
            labelColor: isDarkStyle ? Color(0xff810906) : Color(0xE5FFFFFF),
            indicator: CustomIndicator(
              height: 4.h,
              width: 16.w,
              useGradient: true,
              gradientColors: [
                isDarkStyle ? Color(0xff810906) : Color(0xffE1351F),
                isDarkStyle ? Color(0xff810906) : Color(0xffE1351F),
              ],
              offsetY: 6,
            ),
            controller: logic.tabController,
          ),
        ),
        Expanded(
          child: Stack(
            fit: StackFit.expand,
            children: [
              if (widget.isDarkStyle) Image.asset("aw_bg.webp".homePath),
              TabBarView(
                controller: logic.tabController,
                children: List.generate(logic.homePageTabArr.length, (index) {
                  ModuleData module = logic.homePageTabArr[index];
                  if (module.type == 1 || module.type == 3) {
                    if (module.showType == 3) {
                      return HomeTabSectionPage(index, module, isDarkStyle: isDarkStyle).keepAlive;
                    } else {
                      return HomeTabSortPage(index, module, isDarkStyle: isDarkStyle).keepAlive;
                    }
                  } else if (module.isACG) {
                    return CartoonSubDetailPage(
                      tagData: module,
                      type: CommunityType.Cartoon,
                    ).keepAlive;
                    // if (module.showType == 3) {
                    //   return HomeSubModulePage<ACGController>(
                    //     module,
                    //     index: index,
                    //   ).keepAlive;
                    // } else {
                    //   return HomeTabSortPage(index, module, isDarkStyle: isDarkStyle).keepAlive;
                    // }
                  } else {
                    return HomeTabSortPage(index, module, isDarkStyle: isDarkStyle).keepAlive;
                  }
                }),
              )
            ],
          ),
        ),
      ],
    );
  }
}
